package com.yonyou.pmclouds.billview.plugin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.basecom.util.StorageFactory;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.repeatwork.entity.RepeatWorkVO;
import com.yonyou.pmclouds.workflow.service.rmiitf.IWorkFlowService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class RepeatWorkPlugin implements IBillViewCustomPlugin {

    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;
    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private StorageFactory storageFactory;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private OrganizationQuery organizationQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IWorkFlowService iworkFlowService;
    @Value("${print.perLineNum}")
    private int perLineNum;

    @Override
    public Object[] fillListBuziField(Object[] objects) throws BusinessException {
        if (null == objects || objects.length == 0) {
            return new Object[0];
        }
        RepeatWorkVO[] repeatWorkVOS = new RepeatWorkVO[objects.length];
        for(int i=0;i <objects.length; i ++){
            repeatWorkVOS[i] = (RepeatWorkVO) objects[i];
        }
        //补充创建者姓名
        userInfoQuery.tranUserInfoField(objects,new String[]{CommonFieldConst.CREATOR},new String[]{CommonFieldConst.CREATOR_NAME});
        //补充项目对应的组织信息
        List<String> pkPorjects = Arrays.stream(repeatWorkVOS).map(RepeatWorkVO::getPkProject).collect(Collectors.toList());
        //获取所有项目以及项目对应的组织名称
        Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(pkPorjects.toArray(new String[0]));
        //获取组织信息
        Map<String, OrganizationVO> proToOrgMap =obtailPkorgByProject(projectMap);
        fillRepeatWorkVo(repeatWorkVOS,projectMap,proToOrgMap);
        return objects;
    }

    @Override
    public Map<String, Object[]> fillDetailBuziField(SuperVO superVO, HttpServletRequest request) throws BusinessException {
        Map<String,Object[]> resultMap = new HashMap<String,Object[]>();
        resultMap.put(BusinessObjectConsts.PM_REPEATWORK, new Object[]{superVO});
        return resultMap;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.REPEATWORK_BILLTYPE;
    }

    private Map<String, OrganizationVO> obtailPkorgByProject(Map<String, ProjectVO> projectMap) throws BusinessException {
        Map<String, OrganizationVO> proToOrgMap = new HashMap<String, OrganizationVO>();
        if(projectMap != null && projectMap.size()> 0){
            List<String> pkOrgs = projectMap.values().stream().map(ProjectVO::getPkOrg).filter(vo -> StringUtils.isNotEmpty(vo)).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(pkOrgs)) {
                OrganizationVO[] organizationVOs = organizationQuery.queryByPkSrcs(RuntimeEnvironment.getTenantId(), pkOrgs.toArray(new String[0]));
                proToOrgMap = Arrays.stream(organizationVOs).filter(organizationVO -> StringUtils.isNotEmpty(organizationVO.getPkSrc()))
                        .collect(Collectors.toMap(OrganizationVO::getPkSrc, organizationVO -> organizationVO));
            }
        }
        return proToOrgMap;
    }

    /**
     * 将组织信息填充到复工单。
     * @param repeatWorkVOS
     * @param projectMap
     * @param proToOrgMap
     */
    private void fillRepeatWorkVo(RepeatWorkVO[] repeatWorkVOS,Map<String, ProjectVO> projectMap, Map<String, OrganizationVO> proToOrgMap) throws BusinessException {
        String loginUserId = RuntimeEnvironment.getLoginUserId();
        for (RepeatWorkVO repeatWorkVO: repeatWorkVOS){
            //获取项目信息
            ProjectVO projectVO = projectMap.get(repeatWorkVO.getPkProject());
            if(projectVO != null){
                //赋值项目名以及项目编号
                repeatWorkVO.setProjectName(projectVO.getSname());
                repeatWorkVO.setProjectCode(projectVO.getScode());
            }

            if(proToOrgMap.get(projectVO.getPkOrg()) != null){
                OrganizationVO organizationVO = proToOrgMap.get(projectVO.getPkOrg());
                repeatWorkVO.setPkOrganization(organizationVO.getPkOrganization());
                repeatWorkVO.setOrgName(organizationVO.getSname());
                repeatWorkVO.setPkOrgSrc(organizationVO.getPkSrc());
            }
        }
    }
}
